package com.shuyou;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;

import com.shuyou.net.BookDetail;
import com.shuyou.net.Data;
import com.shuyou.net.JsonParser;
import com.shuyou.net.ServerInfo;
import com.shuyou.net.StaticHttpClient;
import com.shuyou.values.Values;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class BookInfoActivity extends Activity{

	
	String isbn = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_bookinfo);
		
		Intent i = getIntent();
		isbn = i.getStringExtra("bookIsbn");
		
		/*根据已有的一些书籍信息，初始化显示*/
		TextView textBookName = (TextView)findViewById(R.id.bookinfo_bookname);
		textBookName.setText(i.getStringExtra("bookName"));
		TextView textAuthor = (TextView)findViewById(R.id.bookinfo_author);
		textAuthor.setText(i.getStringExtra("bookAuthor"));
		TextView textLabel = (TextView)findViewById(R.id.bookinfo_label);
		textLabel.setText(i.getStringExtra("bookLabel"));
		
		new Thread()
		{
			@Override
			public void run() {
				// TODO Auto-generated method stub
				String strResult = null;
				try {
					Map<String, String> map = new HashMap<String, String>();
					map.put("isbn", isbn);
					map.put("test", "1");
					strResult = StaticHttpClient.doGet(
							Values.BOOK_INDEX_DETAIL, map);
				
					ServerInfo si = (ServerInfo) JsonParser.parseObject(strResult,
							ServerInfo.class);
					if(si.getStatus() == "30001"){
						//不存在该书的信息 30001
						Toast.makeText(BookInfoActivity.this, "30001", Toast.LENGTH_SHORT).show();
					}
					if(si.getStatus() == "10003"){
						//服务器错误 10003
						Toast.makeText(BookInfoActivity.this, "10003", Toast.LENGTH_SHORT).show();
					}
					if(si.getStatus() == "10004"){
						Toast.makeText(BookInfoActivity.this, "10004", Toast.LENGTH_SHORT).show();
					}
					System.out.println(si);
					Message msg = new Message();
					msg.obj = si.getData();
					msg.what = Values.LOAD_BOOK_INFO_SUCCESS;
					handler.sendMessage(msg);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					Message msg = new Message();
					msg.what = Values.NETWORK_ERROR;
					handler.sendMessage(msg);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Message msg = new Message();
					msg.what = Values.NETWORK_ERROR;
					handler.sendMessage(msg);
					e.printStackTrace();
				}
			}
		}.start();
		
		//返回按钮
		findViewById(R.id.bookinfo_back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		
		//借阅本书按钮
		findViewById(R.id.bookinfo_confirm_button).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(BookInfoActivity.this, BookOwnersActivity.class);
				i.putExtra("isbn", isbn);
				startActivity(i);
			}
			
		});
		
	}
	
	private Drawable loadImageFromUrl(String url) {
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Drawable d = Drawable.createFromStream(i, "src");
		return d;
	}
	
	private void DisplayAfterLoad(Data data) {
		BookDetail bookDetail = new BookDetail();
		
		bookDetail = data.getBookDetail();
		
		TextView textBookName = (TextView)findViewById(R.id.bookinfo_bookname);
		textBookName.setText(bookDetail.getBook_name());
		
		TextView textPublicDate = (TextView)findViewById(R.id.bookinfo_publishdate);
		textPublicDate.setText(bookDetail.getPublish_date());
		
		TextView textAuthor = (TextView)findViewById(R.id.bookinfo_author);
		textAuthor.setText(bookDetail.getAuthor());
		
		TextView textLabel = (TextView)findViewById(R.id.bookinfo_label);
		textLabel.setText(bookDetail.getLabel());
		
		TextView textPublisher = (TextView)findViewById(R.id.bookinfo_publisher);
		textPublisher.setText(bookDetail.getPublisher());
		TextView textZancount = (TextView)findViewById(R.id.bookinfo_zancount);
		textZancount.setText(bookDetail.getZan_count());
		TextView textProfile = (TextView)findViewById(R.id.bookinfo_profile);
		textProfile.setText(bookDetail.getProfile());
		//豆瓣分数的显示
		float score = (float) (Float.parseFloat(bookDetail.getScore()) / 2.0);
		RatingBar scoreBar = (RatingBar)findViewById(R.id.bookinfo_bookscore_ratingbar);
		scoreBar.setRating(score);
		TextView textScoreDec = (TextView)findViewById(R.id.bookinfo_bookscore_dec);
		textScoreDec.setText(bookDetail.getScore().substring(0,1));
		TextView textScoreFra = (TextView)findViewById(R.id.bookinfo_bookscore_fra);
		textScoreFra.setText(bookDetail.getScore().substring(1,3));
		
		//异步显示图书logo
		final String logoUrl = bookDetail.getBook_link();
		new Thread(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Drawable logo = (Drawable)loadImageFromUrl(logoUrl);
				Message msg = new Message();
				msg.obj = logo;
				msg.what = Values.LOAD_BOOK_INFO_LOGO_SUCCESS;
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	static class MyInnerHandler extends Handler {
        WeakReference<BookInfoActivity> mActivity;

        MyInnerHandler(BookInfoActivity mAct) {
        	mActivity = new WeakReference<BookInfoActivity>(mAct);
        }
        
		@Override
		public void handleMessage(Message msg) {
			BookInfoActivity theAct = mActivity.get();
			switch(msg.what){
				case Values.LOAD_BOOK_INFO_SUCCESS:
					Data data = (Data)msg.obj;
					System.out.println(data);
					theAct.DisplayAfterLoad(data);
					break;
				case Values.LOAD_BOOK_INFO_LOGO_SUCCESS:
					ImageView iv = (ImageView)theAct.findViewById(R.id.bookinfo_booklogo);
					iv.setImageDrawable((Drawable)msg.obj);
					break;
				case Values.NETWORK_ERROR:
					Toast.makeText(theAct, "网络连接异常,获取详情失败", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
				}
		}	
	}
	MyInnerHandler handler = new MyInnerHandler(this);
	
	
}
